# from django.http import JsonResponse, HttpResponse
# from django.views.decorators.csrf import csrf_exempt
# from django.views.decorators.http import require_http_methods
# import json
# import logging
# from .models import Order
# from utils.alipay_utils import create_alipay_order, verify_sign, query_order, ALIPAY_CONFIG
#
# logger = logging.getLogger(__name__)
#
# @csrf_exempt
# @require_http_methods(['POST'])
# def create_order(request):
#     """创建支付宝支付订单"""
#     try:
#         # 获取请求参数
#         data = json.loads(request.body)
#         order_number = data.get('order_number')
#         total_amount = data.get('total_amount')
#         order_type = data.get('order_type')
#         subject = data.get('subject', '商品购买')
#         body = data.get('body', '商品详情')
#         userid = data.get('userid')
#
#         if not all([order_number, total_amount]):
#             return JsonResponse({'code': 400, 'message': '缺少必要参数'}, status=400)
#
#         # 创建订单记录
#         Order.objects.create(
#             orderno=order_number,
#             order_type=order_type,
#             user_id=userid,
#             zprice=total_amount,
#             status="待支付"
#         )
#
#         # 调用支付宝接口创建订单
#         pay_url = create_alipay_order(order_number, total_amount, subject, body)
#
#         return JsonResponse({
#             'code': 200,
#             'message': '创建订单成功',
#             'data': {
#                 'pay_url': pay_url
#             }
#         })
#
#     except Exception as e:
#         logger.error(f"创建订单失败: {str(e)}")
#         return JsonResponse({'code': 500, 'message': f'创建订单失败: {str(e)}'}, status=500)
#
# @csrf_exempt
# @require_http_methods(['POST'])
# def alipay_notify(request):
#     """支付宝异步通知处理"""
#     try:
#         # 获取支付宝POST过来的数据
#         data = request.POST.dict()
#         logger.info(f"收到支付宝异步通知: {data}")
#
#         # 验证签名
#         if not verify_sign(data, ALIPAY_CONFIG['alipay_public_key']):
#             logger.error("支付宝异步通知验签失败")
#             return HttpResponse('fail')
#
#         # 获取通知数据
#         trade_status = data.get('trade_status')
#         out_trade_no = data.get('out_trade_no')
#         trade_no = data.get('trade_no')
#
#         if trade_status in ('TRADE_SUCCESS', 'TRADE_FINISHED'):
#             # 更新订单状态
#             try:
#                 order = Order.objects.get(orderno=out_trade_no)
#                 order.status = "已支付"
#                 order.save()
#                 logger.info(f"订单 {out_trade_no} 支付成功")
#                 return HttpResponse('success')
#             except Order.DoesNotExist:
#                 logger.error(f"订单 {out_trade_no} 不存在")
#                 return HttpResponse('fail')
#
#         return HttpResponse('success')
#
#     except Exception as e:
#         logger.error(f"处理支付宝异步通知失败: {str(e)}")
#         return HttpResponse('fail')
#
# @csrf_exempt
# @require_http_methods(['GET'])
# def alipay_return(request):
#     """支付宝同步回调处理"""
#     try:
#         # 获取所有GET参数
#         params = request.GET.dict()
#
#         # 验证签名
#         if not verify_sign(params, ALIPAY_CONFIG['alipay_public_key']):
#             return JsonResponse({'code': 400, 'message': '验签失败'}, status=400)
#
#         # 获取订单信息
#         out_trade_no = params.get('out_trade_no')
#         trade_no = params.get('trade_no')
#         total_amount = params.get('total_amount')
#
#         try:
#             # 更新订单状态
#             order = Order.objects.get(orderno=out_trade_no)
#             order.status = "已支付"
#             order.save()
#
#             # 返回支付成功页面
#             return HttpResponse(f'''
#             <html>
#             <head>
#                 <meta charset="utf-8">
#                 <title>支付成功</title>
#                 <style>
#                     body {{
#                         font-family: Arial, sans-serif;
#                         display: flex;
#                         justify-content: center;
#                         align-items: center;
#                         height: 100vh;
#                         margin: 0;
#                         background-color: #f5f5f5;
#                     }}
#                     .success-container {{
#                         text-align: center;
#                         padding: 30px;
#                         background: white;
#                         border-radius: 10px;
#                         box-shadow: 0 0 10px rgba(0,0,0,0.1);
#                     }}
#                     .success-icon {{
#                         color: #52c41a;
#                         font-size: 48px;
#                         margin-bottom: 20px;
#                     }}
#                     .success-title {{
#                         color: #333;
#                         font-size: 24px;
#                         margin-bottom: 15px;
#                     }}
#                     .order-info {{
#                         color: #666;
#                         margin-bottom: 20px;
#                     }}
#                     .back-button {{
#                         background-color: #1890ff;
#                         color: white;
#                         border: none;
#                         padding: 10px 20px;
#                         border-radius: 5px;
#                         cursor: pointer;
#                         text-decoration: none;
#                     }}
#                     .back-button:hover {{
#                         background-color: #40a9ff;
#                     }}
#                 </style>
#             </head>
#             <body>
#                 <div class="success-container">
#                     <div class="success-icon">✓</div>
#                     <h1 class="success-title">支付成功</h1>
#                     <div class="order-info">
#                         <p>订单号: {out_trade_no}</p>
#                         <p>支付宝交易号: {trade_no}</p>
#                         <p>支付金额: ￥{total_amount}</p>
#                     </div>
#                     <a href="http://localhost:5173" class="back-button">返回首页</a>
#                 </div>
#             </body>
#             </html>
#             ''')
#
#         except Order.DoesNotExist:
#             return JsonResponse({'code': 404, 'message': '订单不存在'}, status=404)
#
#     except Exception as e:
#         logger.error(f"处理同步回调失败: {str(e)}")
#         return JsonResponse({'code': 500, 'message': f'处理同步回调失败: {str(e)}'}, status=500)
#
# @require_http_methods(['GET'])
# def query_order_status(request):
#     """查询订单状态"""
#     try:
#         order_number = request.GET.get('order_number')
#         if not order_number:
#             return JsonResponse({'code': 400, 'message': '缺少订单号'}, status=400)
#
#         # 查询支付宝订单状态
#         result = query_order(order_number)
#
#         return JsonResponse({
#             'code': 200,
#             'message': '查询成功',
#             'data': result
#         })
#
#     except Exception as e:
#         logger.error(f"查询订单失败: {str(e)}")
#         return JsonResponse({'code': 500, 'message': f'查询订单失败: {str(e)}'}, status=500)